package com.cloud.order.controller;

import com.cloud.order.client.ProductClient;
import com.cloud.order.converter.OrderConverter;
import com.cloud.order.dto.CartDTO;
import com.cloud.order.dto.OrderDTO;
import com.cloud.order.enums.ResponseCode;
import com.cloud.order.exception.OrderException;
import com.cloud.order.form.OrderForm;
import com.cloud.order.service.OrderService;
import com.cloud.order.utils.JsonUtils;
import com.cloud.order.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductClient productClient;


    /**
     * 1    参数校验
     * 2    查询商品信息（调用商品服务）
     * 3    计算总价
     * 4    扣库存（调用商品服务）
     * 5    订单入库
     */
    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确,orderForm={}", orderForm);
            throw new OrderException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage(), ResponseCode.ILLEGAL_ARGUMENT.getCode());
        }
//        orderForm->orderDTO
        OrderDTO orderDTO = OrderConverter.OrderForm2OrderDTO(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getList())) {
            log.error("【创建订单】购物车信息为空");
            throw new OrderException(ResponseCode.CART_EMPTY);
        }
        OrderDTO order = orderService.createOrder(orderDTO);
//        return ResultVO.createBySuccess(JsonUtils.objectToJsonIncludes(Objects.requireNonNull(order), new String[]{"orderId"}));
        Map map = new HashMap<String,Object>();
        map.put("orderId", order.getOrderId());
        return ResultVO.createBySuccess(map);
    }

    @GetMapping("/decrease")
    public void decreaseStock() {
        productClient.decreaseStock(Arrays.asList(new CartDTO("157875196366160022", 40)));
    }

}
